<style scoped lang="less">
  @import "../../less/switch.less";
</style>
<template>
  <div>
    <!-- 搜索 -->
    <el-form :model="formItem"  label-width="80px" :inline="true" class="demo-form-inline">
      <el-form-item label="活动类型">
        <el-select v-model="formItem.position_id" placeholder="请选择">
          <el-option v-for="item in positionList" :value="item.id" :label="item.name" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="广告名称">
        <el-input v-model="formItem.name" placeholder="活动名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="searchSubmit('formItem')">搜索</el-button>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 10px;">
      <el-button @click="advAddButton()" type="primary" size="mini">添加</el-button>
      <el-button @click.native="deleteAll()" type="danger" size="mini">删除</el-button>
    </div>
    <el-table ref="selection" :data="listData" border tooltip-effect="dark" style="width: 100%"  @cell-dblclick="tableEdit" @selection-change="select">
      <el-table-column fixed type="selection" width="55"></el-table-column>
      <el-table-column prop="type" label="广告位" width="100">
        <template slot-scope="scope">
          {{scope.row.position ? scope.row.position.name : ''}}
        </template>
      </el-table-column>
      <el-table-column prop="title" label="名称" width="200"></el-table-column>
      <el-table-column prop="describe" label="广告图片" show-overflow-tooltip width="300">
        <template slot-scope="scope">
          <div class="demo-image__preview">
            <el-image :src="scope.row.file.path" :preview-src-list="getImgList(scope.row)" style="width:50px;height:50px;borderRadius: 25px;"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="200">
        <template slot-scope="scope">{{ scope.row.sort }}</template>
      </el-table-column>
      <el-table-column prop="sort" label="状态" width="200">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status"
                     active-color="#00A854"
                     active-text="正常"
                     :active-value="1"
                     class="demo"
                     inactive-color="#F04134"
                     inactive-text="冻结"
                     :inactive-value="2"
                     @change="changeSwitch(scope.$index)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="320">
        <template slot-scope="scope">
          <el-button @click.native.prevent="edit(scope.$index)" type="primary" size="mini">编辑</el-button>
          <el-button @click.native.prevent="del(scope.$index)" type="danger" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="text-align : right; float : right; margin-top: 10px;">
      <!--<span class="demonstration">完整功能</span>-->
      <el-pagination
              @size-change="handlePageSize"
              @current-change="handlePage"
              :current-page="pageNum"
              :page-sizes="[10, 50, 100, 200]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageTotal">
      </el-pagination>
    </div>
    <!-- 活动添加修改 -->
    <el-dialog :visible.sync="advAdd" :title="titleStr" width="500px">
      <el-form ref="activity" :model="formAdd" :rules="formAddValidate" label-width="80px" class="demo-ruleForm">
        <el-form-item label="广告位" prop="position_id">
          <el-select v-model="formAdd.position_id" placeholder="请选择">
            <el-option v-for="item in positionList" :value="item.id" :label="item.name" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="广告名称" prop="title">
          <el-input v-model="formAdd.title" style="width:300px;"  placeholder="请输入广告名称"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="images">
          <el-upload
                  ref="upload"
                  class="avatar-uploader"
                  :action="fileUpload"
                  :show-file-list="false"
                  :on-success="handleSuccess"
                  :before-upload="beforeAvatarUpload">
            <img v-if="imgUrl" :src="imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formAdd.sort" :min="1" :max="10000" style="width:300px;"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.native="addSubmit('formAdd')">提交</el-button>
          <el-button @click="addCancel()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import axios from "@/axios";
  import moment from 'moment';
  import { isIntNum,getHeaders } from "@/assets/js/common";
  export default {
    data() {
      return {
        loading: false,
        base: {},
        imgUrl: "",
        titleStr: "",
        // 搜索字段
        formItem: {
          position_id: "",
          name: "",
        },
        formAdd: {
          position_id: "",
          title: "",
          images: "",
          type: 1,
          url: "",
          start_time: "",
          end_time: "",
          status: 1,
          sort : 1
        },
        formAddValidate: {
          position_id: [
            {
              type: 'number',
              required: true,
              message: "请选择广告位",
              trigger: "change"
            }
          ],
          title: [
            {
              required: true,
              message: "名称不能为空",
              trigger: "blur"
            }
          ],
          images: [
            {
              type: 'number',
              required: true,
              message: "请上传图片",
              trigger: "change"
            }
          ],
        },
        advAdd:false,
        listData: [], // 广告列表
        positionList: [], // 广告位列表
        ids:[],
        headers: {},
        credentials: true,
        fileUpload: "",
        fileUrl:  "",
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      };
    },
    mounted() {
      this.base = JSON.parse(sessionStorage.base);
      this.fileUpload = this.base.domain_name + "/api/file/upload";
      this.headers = getHeaders(localStorage._token);
      // 广告位列表
      this.getAdvPositionList();
      // 广告列表
      this.getList();
    },
    methods: {
      tableEdit(row, column, cell, event) {
        let vm = this;
        if (column.label) {
          // 获取当前的值
          var beforeVal = event.target.textContent;
          event.target.innerHTML = "";
          let str = `<div class='cell'>
            <div class='el-input'>
              <input type='text' placeholder='请输入内容' class='el-input__inner'>
            </div>
        </div>`;
          cell.innerHTML = str;
          // 获取双击后生成的input  根据层级嵌套会有所变化
          let cellInput = cell.children[0].children[0].children[0];
          cellInput.value = beforeVal;
          cellInput.focus(); // input自动聚焦
          // 失去焦点后  将input移除
          cellInput.onblur = function() {
            let onblurCont = `<div class='cell'>${cellInput.value}</div>`;
            cell.innerHTML = onblurCont; // 换成原有的显示内容
            // 调用axios接口
            if (column.property === 'sort'){
              axios
                .post("/admin/adv/updateSort", {
                  id: row.id,
                  sort: cellInput.value
                })
                .then(response => {
                  let status = response.status;
                  let data = response.data;
                  if (data.code === 200) {
                    vm.$message({
                      type: 'success',
                      message: "操作成功!",
                      onClose: function (msg) {
                        this.getActivity();
                      }
                    });
                  } else {
                    vm.$message.info(data.message);
                  }
                })
                .catch(error => {
                  // vm.$Message.info("网络或服务器异常");
                });
            }
          };
        }
      },
      // 图片预览
      getImgList(row){
        let images = [];
        if (row.file) {
          images.push(row.file.path);
        }
        return images
      },
      //获取勾选参数
      select(val) {
        let vm = this;
        vm.ids = [];
        for (let i in val) {
          vm.ids.push(val[i].id);
        }
      },
      // 批量删除
      deleteAll() {
        let vm = this;
        if (vm.ids.length < 1) {
          vm.$message.error("请勾选数据！");
          return false;
        }
        this.$confirm("是否确认删除吗？", "确认删除" , {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios
            .post("/admin/adv/delete", {
              ids: vm.ids
            })
            .then(response => {
              let status = response.status;
              let data = response.data;
              if (data.code == 200) {
                vm.$message({
                  type: 'success',
                  content: "操作成功!",
                  onClose: function(msg) {
                    vm.getList();
                    vm.ids = [];
                  }
                });
              } else {
                vm.$message.error(data.message);
              }
            })
            .catch(error => {
              //vm.$Message.info("网络或服务器异常");
            });
          }).catch(() => {
            vm.ids = [];
            this.$refs.selection.selectAll(false);
          });
      },
      //搜索
      searchSubmit() {
        this.pageNum = 1;
        this.getList();
      },
      //当前页数
      handlePage(value) {
        this.pageNum = value;
        this.getList();
      },
      //每页显示条数
      handlePageSize(value) {
        this.pageSize = value;
        this.getList();
      },
      // 获取广告位列表
      getAdvPositionList() {
        let vm = this;
        axios
          .post("/admin/adv/position/getIdAndName", {

          })
          .then(response => {
            let data = response.data;
            if (data.code == 200) {
              let result = data.data;
              vm.positionList = data.data;
            } else {
              vm.$message.info(data.message);
            }
          })
          .catch(error => {
            // vm.$Message.info("网络或服务器异常");
          });
      },
      //获取广告列表
      getList() {
        let vm = this;
        axios
          .post("/admin/adv/get-lists", {
            page: this.pageNum,
            limit: this.pageSize,
            name: this.formItem.name,
            position_id: this.formItem.position_id
          })
          .then(response => {
            let data = response.data;
            if (data.code == 200) {
              let result = data.data;
              vm.pageTotal = result.total;
              vm.listData = result.list;
            } else {
              vm.$message.info(data.message);
            }
          })
          .catch(error => {
            // vm.$Message.info("网络或服务器异常");
          });
      },
      //删除
      del: function (index = "") {
        let vm = this;
        //判断单条多条操作
        vm.ids = [];
        if (!isIntNum(index)) {
          vm.ids.push(vm.listData[index].id);
        } else {
          if (vm.ids.length < 1) {
            vm.$message.error("请勾选数据！");
            return false;
          }
        }
        this.$confirm("是否确认删除吗？", "确认删除" , {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios
            .post("/admin/adv/delete", {
              ids: vm.ids
            })
            .then(response => {
              let status = response.status;
              let data = response.data;
              if (data.code == 200) {
                vm.$message({
                  type: 'success',
                  message: "操作成功!",
                  onClose: function (msg) {
                    vm.getAdmin();
                    vm.ids = [];
                  }
                });
              } else {
                vm.$message.error(data.message);
              }
            })
            .catch(error => {
              //vm.$Message.info("网络或服务器异常");
            });
        }).catch(() => {
          vm.ids = [];
          this.$refs.selection.selectAll(false);
        });
      },
      // 添加框取消
      addCancel() {
        this.advAdd = false;
        this.imgUrl = '';
        this.formAdd.id = "";
        this.formAdd.position_id = "";
        this.formAdd.title = "";
        this.formAdd.type = 1;
        this.formAdd.info_id = "";
        this.formAdd.images = "";
        this.formAdd.url = "";
        this.formAdd.start_time = "";
        this.formAdd.end_time = "";
        this.formAdd.status = 0;
        this.formAdd.sort = 1;
      },
      // 添加处理
      addSubmit(name) {
        let vm = this;
        // console.log(this.checkAllId);
        vm.formAdd.start_time = vm.formAdd.start_time ? moment(this.formAdd.start_time).format('YYYY-MM-DD HH:mm:ss') : "";
        vm.formAdd.end_time = vm.formAdd.end_time ? moment(this.formAdd.end_time).format('YYYY-MM-DD HH:mm:ss') : "";
        vm.$refs.activity.validate(valid => {
          if (valid) {
            axios
            .post("/admin/adv/store", vm.formAdd)
              .then(response => {
                let status = response.status;
                let data = response.data;
                if (data.code == 200) {
                  vm.advAdd = false;
                  vm.formAdd.id = "";
                  vm.formAdd.position_id = "";
                  vm.formAdd.title = "";
                  vm.formAdd.type = 1;
                  vm.formAdd.info_id = "";
                  vm.formAdd.images = "";
                  vm.formAdd.url = "";
                  vm.formAdd.start_time = "";
                  vm.formAdd.end_time = "";
                  vm.formAdd.status = 0;
                  vm.formAdd.sort = 1;
                  vm.$message({
                    type: 'success',
                    message: "操作成功!",
                    onClose: function (msg) {
                      vm.getList();
                    }
                  });
                } else {
                  vm.$message.error(data.message);
                }
              })
              .catch(error => {
              // vm.$Message.error("网络或服务器异常");
              });
          } else {
            // vm.$Message.error("Fail!");
          }
        });
      },
      // 添加
      advAddButton() {
        let vm = this;
        vm.titleStr = '添加';
        vm.advAdd = true;
      },
      // 编辑
      edit(index) {
        let vm = this;
        vm.titleStr = '编辑';
        vm.formAdd.id = vm.listData[index].id;
        vm.formAdd.position_id = vm.listData[index].position_id;
        vm.formAdd.type = vm.listData[index].type;
        vm.formAdd.title = vm.listData[index].title;
        vm.formAdd.info_id = vm.listData[index].info_id;
        vm.formAdd.images = vm.listData[index].images;
        vm.formAdd.url = vm.listData[index].url;
        vm.formAdd.start_time = vm.listData[index].start_time;
        vm.formAdd.end_time = vm.listData[index].end_time;
        vm.formAdd.status = vm.listData[index].status;
        vm.formAdd.sort = vm.listData[index].sort;
        vm.imgUrl = vm.listData[index].file.path;
        vm.advAdd = true;
      },
      //排序
      sort(index) {
        let vm = this;
        // console.log(vm.listData[index]);
        axios
          .post("/admin/adv/updateSort", {
            id: vm.listData[index].id,
            sort: vm.listData[index].sort
          })
          .then(response => {
            let data = response.data;
            if (data.code == 200) {
              vm.$message({
                type: 'success',
                content: "操作成功!",
                onClose: function (msg) {
                }
              });
              vm.getList();
            } else {
              vm.$message.error(data.message);
            }
          })
          .catch(error => {
            // vm.$Message.info("网络或服务器异常");
          });
      },
      // 图片上传处理
      handleSuccess(res, file) {
        let vm = this;
        if (res.code == 200) {
          this.imgUrl = res.img_path;
          this.formAdd.images = res.file;
        } else {
          vm.$message.error(res.message);
        }
      },
      //更改状态
      changeSwitch(index) {
        let vm = this;
        //打开是true,已经处理0
        if (vm.listData[index].status == 1) {
          status = 2;
        } else {
          status = 1;
        }
        axios
          .post("/admin/adv/enabled", {
            adv_id: vm.listData[index].id,
            status: status
          })
          .then(response => {
            let status = response.status;
            let data = response.data;
            if (data.code === 200) {
              vm.$message({
                type: 'success',
                message: "操作成功!",
                onClose: function (msg) {
                  vm.getList();
                }
              });
            } else {
              vm.$message.error(data.message);
            }
          })
          .catch(error => {
            // vm.$Message.info("网络或服务器异常");
          });
      },
    }
  };
</script>